package com.ittao.taoaicodeapp.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;

/**
 * Spring Session Redis 配置
 * 解决SpringSession存储乱码和过期时间问题
 */
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 7200)
public class SpringSessionConfig {

    /**
     * 配置Redis序列化器，解决SpringSession存储乱码问题
     * 支持Java 8时间类型序列化
     * @return GenericJackson2JsonRedisSerializer
     */
    @Bean("springSessionDefaultRedisSerializer")
    public GenericJackson2JsonRedisSerializer springSessionDefaultRedisSerializer() {
        // 创建自定义的ObjectMapper，配置忽略未知字段并支持Java 8时间类型
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 注册Java 8时间模块，支持LocalDateTime等时间类型
        objectMapper.registerModule(new JavaTimeModule());
        return new GenericJackson2JsonRedisSerializer(objectMapper);
    }

    /**
     * 配置Cookie序列化器，确保Session ID正确传输
     * @return
     */
    @Bean
    public CookieSerializer cookieSerializer() {
        DefaultCookieSerializer serializer = new DefaultCookieSerializer();
        serializer.setCookieName("JSESSIONID");
        serializer.setCookiePath("/");
        serializer.setUseHttpOnlyCookie(true);
        serializer.setUseSecureCookie(false);
        serializer.setCookieMaxAge(7200);
        return serializer;
    }

    /**
     * 禁用Redis配置命令，避免在某些Redis环境下出现问题
     * @return
     */
    @Bean
    public ConfigureRedisAction configureRedisAction() {
        return ConfigureRedisAction.NO_OP;
    }
}
